import axios from 'axios'
import { cloneDeep } from 'lodash'
import { safe } from '.'
import { MaterialModel } from '~/model/MaterialModel'
import { MaterialSerializer } from '~/serializer/MaterialSerializer'

// 物料相关接口
export abstract class MaterialApi {
  private static quering?: Promise<MaterialModel[]>
  private static cache?: MaterialModel[]
  private static clearCache() {
    delete this.quering
    delete this.cache
  }

  public static async getAll(): Promise<MaterialModel[]> {
    // use cache
    if (this.cache) {
      return cloneDeep(this.cache)
    }

    // pend
    if (this.quering) {
      return await this.quering
    }

    const inner: () => Promise<MaterialModel[]> = async () => {
      const res = await axios.get('materials/')
      const arr = await res.data
      const ret = arr.map((x: any) => MaterialSerializer.deserialize(x))
      this.cache = ret
      return ret
    }

    this.quering = inner()
    return await this.quering
  }

  public static async add(item: MaterialModel) {
    this.clearCache()
    return safe(() => axios.post(
      'materials/', MaterialSerializer.serialize(item),
    ))
  }

  public static async remove(id: number) {
    this.clearCache()
    return safe(() => axios.delete(
      `materials/${id}/`,
    ))
  }

  public static async update(id: number, item: MaterialModel) {
    this.clearCache()
    return safe(() => axios.put(
      `materials/${id}/`,
      MaterialSerializer.serialize(item),
    ))
  }

  public static async takeOff(id: number) {
    this.clearCache()
    return safe(() => axios.put(
      `materials/${id}/take_off/`,
    ))
  }

  public static async relist(id: number) {
    this.clearCache()
    return safe(() => axios.put(
      `materials/${id}/relist/`,
    ))
  }
}
